//
//  ByViewShopsDetailHeader.m
//  chequanbao_ios
//
//  Created by pro on 17/5/9.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByViewShopsDetailHeader.h"

#import "ByViewStarMark.h"

#import "JZLocationConverter.h"

#import <MapKit/MapKit.h>

#import "ByViewDetailHeaderCarousel.h"

@implementation ByViewShopsDetailHeader
{
//    UIImageView     *_detailImageView;
    ByViewDetailHeaderCarousel      *_carousel;
    UILabel                         *_nameLabel;
    ByViewStarMark                  *_starView;
    UILabel                         *_sellMarkView;
    UIButton                        *_buyBtn;
    UIView                          *_sepline;
    UIImageView                     *_addressImageView;
    UILabel                         *_addressLabel;
    UIButton                        *_locationBtn;
    UIButton                        *_callBtn;
    
    // 后期添加
    UIView                          *_lineView;
    UILabel                         *_infoLabel;
    UILabel                         *_describeLabel;
    UIView                          *_bgImgView;

}
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        self.layer.cornerRadius = 10;

        [self setupUI];
    }
    return self;
}
- (void)setupUI {
    
    // 主图
//    _detailImageView = [[UIImageView alloc] init];
//    _detailImageView.backgroundColor = [UIColor greenColor];
//    [self addSubview:_detailImageView];
//    _carousel = [[ByViewDetailHeaderCarousel alloc] init];
//    [self addSubview:_carousel];
    
    _buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _buyBtn.titleLabel.font = FONT(15);
    _buyBtn.backgroundColor = rgba(23, 160, 255, 1);
    [_buyBtn setTitle:@"买单" forState:UIControlStateNormal];
    [_buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_buyBtn addTarget:self action:@selector(buy) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_buyBtn];
    
    
    _nameLabel = [[UILabel alloc] init];
    _nameLabel.numberOfLines = 0;
    _nameLabel.adjustsFontSizeToFitWidth = YES;
    _nameLabel.font = FONT(16);
    _nameLabel.textColor = [UIColor blackColor];
    _nameLabel.textAlignment = NSTextAlignmentLeft;
    [self addSubview:_nameLabel];
    
    _starView = [[ByViewStarMark alloc] init];
    [self addSubview:_starView];
    
    _sellMarkView = [[UILabel alloc] init];
    _sellMarkView.adjustsFontSizeToFitWidth = YES;
    _sellMarkView.font = FONT(14);
    _sellMarkView.textColor = [UIColor lightGrayColor];
    _sellMarkView.textAlignment = NSTextAlignmentLeft;
    [self addSubview:_sellMarkView];
  
    _sepline = [[UIView alloc] init];
    _sepline.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    [self addSubview:_sepline];

    
    _addressImageView = [[UIImageView alloc] init];
    _addressImageView.image = [UIImage imageNamed:@"Shops_star_weizhi"];
    [self addSubview:_addressImageView];
    
    _addressLabel = [[UILabel alloc] init];
    _addressLabel.numberOfLines = 0;
    _addressLabel.adjustsFontSizeToFitWidth = YES;
    _addressLabel.font = FONT(15);
    _addressLabel.textColor = [UIColor blackColor];
    _addressLabel.textAlignment = NSTextAlignmentLeft;
    [self addSubview:_addressLabel];
    
    _addressLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addressTap)];
    [_addressLabel addGestureRecognizer:tap];
    
    _locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationBtn.backgroundColor = [UIColor cyanColor];
//    [self addSubview:_locationBtn];
 
    _callBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_callBtn setImage:[UIImage imageNamed:@"Shops_star_dianhua"] forState:UIControlStateNormal];
    [self addSubview:_callBtn];
    
    // 后期添加
    _lineView = [[UIView alloc] init];
    _lineView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    [self addSubview:_lineView];
    
    _infoLabel = [[UILabel alloc] init];
    [self addSubview:_infoLabel];
    
    _describeLabel = [[UILabel alloc] init];
    _describeLabel.numberOfLines = 0;
    _describeLabel.font = FONT(15);
    _describeLabel.textColor = [UIColor lightGrayColor];
    [self addSubview:_describeLabel];
    
    _bgImgView = [[UIView alloc] init];
    [self addSubview:_bgImgView];

}

- (void)setShopItemModel:(ByModelShopsListItem *)shopItemModel {
    
    _shopItemModel = shopItemModel;
    
    [self setNeedsLayout];
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    /*
     模拟数据
     */
    NSString *name = self.shopItemModel.name;
    CGFloat starCount = self.shopItemModel.grade.floatValue;
    NSString *sells = [NSString stringWithFormat:@"%@", self.shopItemModel.monthly_sales];
    NSString *money = [NSString stringWithFormat:@"%@", self.shopItemModel.price];
    NSString *address = self.shopItemModel.position;
    
    NSLog(@"%@",self.shopItemModel.detail);
    // 后期添加(测试数据)
    NSString *infoTitle,*detail;
    NSArray *imgs;
    if ([self.shopItemModel.detail isKindOfClass:[NSDictionary class]]) {
        infoTitle = self.shopItemModel.detail[@"title"];
        detail  = self.shopItemModel.detail[@"detail"];
        imgs = [self.shopItemModel.detail[@"img"] componentsSeparatedByString:@","];
    }
 
    
    _nameLabel.text = name;
    _sellMarkView.text = [NSString stringWithFormat:@"人均：￥%@ 月售：%@", money, sells];
    _addressLabel.text = address;
    
    CGFloat margin = 10;
    CGFloat x, y, width, height;
    
    x = 0;
    y = 0;
    width = self.width;
    height = self.width * 8 / 15;
//    height = (int)(width / 2);
//    _carousel.frame = CGRectMake(x, y, width, height);
//    [_detailImageView setImageWithURL:[NSURL URLWithString:self.shopItemModel.main_img_urlstr] placeholderImage:DEFAULT_IMAGE_2_1 completed:nil];
    _carousel = [[ByViewDetailHeaderCarousel alloc] initWithFrame:CGRectMake(x, y, width, height) timerDuration:3];
    _carousel.imageURLStringDatas = [self.shopItemModel.imgs copy];
    [self addSubview:_carousel];
    
    // 添加遮罩层
//    CAShapeLayer *layer = [CAShapeLayer layer];
//    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:_detailImageView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(self.layer.cornerRadius, self.layer.cornerRadius)];
//    layer.path = path.CGPath;
//    layer.fillColor = [UIColor whiteColor].CGColor;
//    _detailImageView.layer.mask = layer;
    
    x = 0;
    y = 0;
    width = 80;
    height = 30;
    _buyBtn.frame = CGRectMake(x, y, width, height);
    _buyBtn.layer.cornerRadius = 4;
    _buyBtn.right = self.width - 15;
    _buyBtn.top = _carousel.bottom + 15;
    
    x = margin;
    y = _carousel.bottom + margin;
    width = _buyBtn.left - margin - x;
    height = [name getRectOfStringWithSize:CGSizeMake(width, 10000) font:16].size.height;
    _nameLabel.frame = CGRectMake(x, y, width, height);
    
    x = _nameLabel.left;
    y = _nameLabel.bottom + margin;
    width = 16 * 5;
    height = 16;
    [_starView setFrameOverride:CGRectMake(x, y, width, height)];
    [_starView setRatio:starCount / 5.0];

    x = _starView.right + margin;
    y = _starView.top;
    width = _nameLabel.right - x;
    height = _starView.height;
    _sellMarkView.frame = CGRectMake(x, y, width, height);
    
    x = margin;
    y = _starView.bottom + margin;
    width = self.width - x * 2;
    height = 1;
    _sepline.frame = CGRectMake(x, y, width, height);

    x = margin;
    y = _sepline.bottom + margin;
    width = 15;
    height = 15;
    _addressImageView.frame = CGRectMake(x, y, width, height);

    x = _addressImageView.right + 5;
    y = _addressImageView.top;
    width = self.width - 100;
    height = [address getRectOfStringWithSize:CGSizeMake(width, 100000) font:15].size.height;
    _addressLabel.frame = CGRectMake(x, y, width, height);

//    x = 0;
//    y = _addressLabel.top;
//    width = 25;
//    height = 25;
//    _locationBtn.frame = CGRectMake(x, y, width, height);
//    _locationBtn.right = self.width - 30;
    
    x = 0;
    y = 0;
    width = 50;
    height = width;
    _callBtn.frame = CGRectMake(x, y, width, height);
    _callBtn.right = self.width - 10;
    _callBtn.y = _addressLabel.y;
    [_callBtn setImageEdgeInsets:UIEdgeInsetsMake(14, 14, 14, 14)];
    [_callBtn addTarget:self action:@selector(call) forControlEvents:UIControlEventTouchUpInside];

   // 后期添加
    x = margin;
    y = MAX(_addressLabel.bottom, _callBtn.bottom) + 10;
    if (infoTitle.length != 0 || detail.length != 0) {
        width = self.width - x * 2;
        height = 1;
    }else{
        width = 0;
        height = 0;
    }
    _lineView.frame = CGRectMake(x, y, width, height);

    x = margin;
    if (infoTitle.length != 0) {
        y = _lineView.bottom + 15;
        width = self.width - x * 2;
        height = 15;
    }else{
        width = 0;
        height = 0;
    }
    _infoLabel.frame = CGRectMake(x, y, width, height);
    _infoLabel.text = infoTitle;
    
    x = margin;
    if (detail.length != 0) {
        y = _infoLabel.bottom + 15;
        width = self.width - x * 2;
        height = [detail getRectOfStringWithSize:CGSizeMake(width, MAXFLOAT) font:15].size.height;
    }else{
        width = 0;
        height = 0;
    }
    _describeLabel.frame = CGRectMake(x, y, width, height);
    _describeLabel.text = detail;
    
    x = margin;
    if (imgs.count != 0) {
        y = _describeLabel.bottom + 15;
        width = (self.width - margin * 5) / 4;
        for (int i = 0; i < imgs.count; i ++) {
            CGFloat img_x = width * (i % 4) + margin * (i % 4);
            CGFloat img_y = width *(i / 4) + margin * (i / 4);
            UIImageView *menuImg = [[UIImageView alloc] initWithFrame:CGRectMake(img_x, img_y, width, width)];
            [menuImg setImageWithURL:[NSURL URLWithString:BOYE_PICTURE_VIEW_URL(imgs[i])] placeholderImage:DEFAULT_IMAGE options:nil];
            [_bgImgView addSubview:menuImg];
        }
        _bgImgView.frame = CGRectMake(x, y, self.width - margin * 2, _bgImgView.subviews.lastObject.bottom + 10);
    }else{
        width = 0;
        height = 0;
        _bgImgView.frame = CGRectMake(x, y, width, height);
    }
    self.height = _bgImgView.bottom;
//    self.height = MAX(_callBtn.bottom, _addressLabel.bottom) + 10;
    
    // 通知
    [[NSNotificationCenter defaultCenter] postNotificationName:KDetailHeaderDidLayout object:nil];
}

- (void)addressTap {
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]])// -- 使用 canOpenURL 判断需要在info.plist 的 LSApplicationQueriesSchemes 添加
    {
        double latitude = self.location.coordinate.latitude;
        double longitude = self.location.coordinate.longitude;
        NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin=%f,%f&destination=%@,%@&mode=driving", latitude, longitude, self.shopItemModel.lat, self.shopItemModel.lng];
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *mapUrl = [NSURL URLWithString:urlString];
        [[UIApplication sharedApplication] openURL:mapUrl];
        
    }else{
        
        [self onDaoHangForIOSMap];
    }
}
#pragma mark  导航 - iosMap
-(void)onDaoHangForIOSMap
{
    // 起点
    CLLocationCoordinate2D coor = [JZLocationConverter bd09ToGcj02:self.location.coordinate];
    MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coor addressDictionary:nil]];
    // 目的地的位置
    CLLocation *location2 = [[CLLocation alloc]initWithLatitude:[self.shopItemModel.lat floatValue] longitude:[self.shopItemModel.lng floatValue]];
    CLLocationCoordinate2D coor3 = location2.coordinate;
    CLLocationCoordinate2D coor2 = [JZLocationConverter bd09ToGcj02:coor3];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coor2 addressDictionary:nil]];
    
    NSArray *items = [NSArray arrayWithObjects:currentLocation, toLocation, nil];
    NSDictionary *options = @{ MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsMapTypeKey: [NSNumber numberWithInteger:MKMapTypeStandard], MKLaunchOptionsShowsTrafficKey:@YES };
    // 打开苹果自身地图应用，并呈现特定的item
    [MKMapItem openMapsWithItems:items launchOptions:options];
    
}

- (void)call {
    NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@", _shopItemModel.contact_number];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (void)buy {
    if (!BY_USER) {
        ByUILoginVC *vc = [[ByUILoginVC alloc] init];
        ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
        [self.viewController presentViewController:navi animated:YES completion:nil];
        return;
    }
    if (self.buyBlock) {
        self.buyBlock();
    }
}

@end
